from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from contextlib import asynccontextmanager

from app.database import connect_to_mongodb, close_mongodb_connection, create_indexes, get_database_stats, ping_database
from app.routers import visa, discourse

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时连接数据库
    await connect_to_mongodb()
    await create_indexes()
    yield
    # 关闭时断开数据库连接
    await close_mongodb_connection()

app = FastAPI(
    title="Visa Tracker API",
    description="基于 FastAPI 的签证追踪 API，集成 Discourse 和网页爬取功能，使用 MongoDB 数据库",
    version="1.0.0",
    lifespan=lifespan
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(visa.router)
app.include_router(discourse.router)

@app.get("/")
async def root():
    """根路径，返回 API 信息"""
    return {
        "message": "Visa Tracker API",
        "version": "1.0.0",
        "database": "MongoDB",
        "docs": "/docs",
        "redoc": "/redoc"
    }

@app.get("/health")
async def health_check():
    """健康检查端点"""
    db_status = await ping_database()
    return {
        "status": "healthy" if db_status else "unhealthy",
        "database": "connected" if db_status else "disconnected"
    }

@app.get("/database/stats")
async def database_stats():
    """获取数据库统计信息"""
    stats = await get_database_stats()
    return {
        "database_type": "MongoDB",
        "collections": stats
    }

@app.get("/test/requests")
async def test_requests():
    """测试 requests 库"""
    import requests
    try:
        response = requests.get("https://httpbin.org/json")
        return {"status": "success", "data": response.json()}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@app.get("/test/beautifulsoup")
async def test_beautifulsoup():
    """测试 BeautifulSoup 库"""
    from bs4 import BeautifulSoup
    import requests
    
    try:
        response = requests.get("https://httpbin.org/html")
        soup = BeautifulSoup(response.text, 'html.parser')
        title = soup.find('title').text if soup.find('title') else "No title found"
        return {"status": "success", "title": title}
    except Exception as e:
        return {"status": "error", "message": str(e)}

if __name__ == "__main__":
    import sys
    import os
    from pathlib import Path
    
    # 确保项目根目录在 Python 路径中
    project_root = Path(__file__).parent.parent
    sys.path.insert(0, str(project_root))
    
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
